
const { Server } = require("socket.io")
const db = require('../db/index')
const initSocket = (httpServer) => {
  const io = new Server(httpServer, {
    cors: {
      origin: process.env.NODE_ENV === 'production' ? '你的生产环境域名' : '*',
      methods: ["GET", "POST"],
      credentials: true
    }
  });

  // 用户连接管理
  const onlineUsers = new Map();

 // Socket.IO 连接处理
io.on('connection', (socket) => {
  console.log(`User connected: ${socket.id}`);

  // 用户登录
  socket.on('login', async (userId) => {
    onlineUsers.set(userId, socket.id);
     await  db.query('UPDATE users SET online = TRUE WHERE user_id = ?', [userId]);
    console.log(`User ${userId} logged in`);
  });

  // 用户断开连接
  socket.on('disconnect', async () => {
    console.log(`User disconnected: ${socket.id}`);
    // 找到断开连接的用户ID并更新在线状态
    for (const [userId, sid] of onlineUsers.entries()) {
      if (sid === socket.id) {
        await db.query('UPDATE users SET online = FALSE WHERE id = ?', [userId]);
        onlineUsers.delete(userId);
        console.log(`User ${userId} logged out`);
        break;
      }
    }
  });

  // 私发消息
  socket.on('private-message', async ({ senderId, receiverId, content }) => {
    const receiverSocketId = onlineUsers.get(receiverId);
    if (receiverSocketId) {
      // 保存消息到数据库
      const [result] = await db.query(
        'INSERT INTO messages (sender_id, receiver_id, content) VALUES (?, ?, ?)',
        [senderId, receiverId, content]
      );
      
      const message = {
        id: result.insertId,
        senderId,
        receiverId,
        content,
        created_at: new Date()
      };
      
      // 发送给接收者
      io.to(receiverSocketId).emit('private-message', message);
      
      // 发送给发送者（确认消息已发送）
      socket.emit('private-message', message);
    } else {
      // 接收者不在线，只保存消息
    await   db.query(
        'INSERT INTO messages (sender_id, receiver_id, content) VALUES (?, ?, ?)',
        [senderId, receiverId, content]
      );
      
      // 通知发送者接收者不在线
      socket.emit('user-offline', receiverId);
    }
  });

  // 群组消息
  socket.on('group-message', async ({ senderId, groupId, content }) => {
    // 保存消息到数据库
    const [result] = await db.query(
      'INSERT INTO messages (sender_id, group_id, content) VALUES (?, ?, ?)',
      [senderId, groupId, content]
    );
    
    const message = {
      id: result.insertId,
      senderId,
      groupId,
      content,
      created_at: new Date(),
      isGroup: true
    };
    
    // 获取群组成员
    const [members] = await db.query(
      'SELECT user_id FROM group_members WHERE group_id = ?',
      [groupId]
    );
    
    // 发送给所有在线的群组成员
    members.forEach(member => {
      const memberId = member.user_id;
      const memberSocketId = onlineUsers.get(memberId);
      if (memberSocketId && memberId !== senderId) {
        io.to(memberSocketId).emit('group-message', message);
      }
    });
    
    // 发送给发送者（确认消息已发送）
    socket.emit('group-message', message);
  });

  // 获取未读消息
  socket.on('get-unread-messages', async (userId) => {
    const [messages] = await db.query(
      `SELECT * FROM messages 
      WHERE receiver_id = ? AND is_read = FALSE`,
      [userId]
    );
    
    // 标记为已读
  await db.query(
      'UPDATE messages SET is_read = TRUE WHERE receiver_id = ?',
      [userId]
    );
    
    socket.emit('unread-messages', messages);
  });
});

  return io;
};

module.exports = initSocket;